﻿// Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using CefSharp.WinForms;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

namespace CefSharp.MinimalExample.WinForms
{
    public class Program
    {
        [STAThread]
        public static void Main()
        {

            //修改CEFsharp的路径
            AppDomain.CurrentDomain.AssemblyResolve += OnResolveAssembly;
            CefSettingInit.InitializeCefSetting(Application.StartupPath);

            //var executingFolder = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            //If libcef.dll doesn't exist in our executing folder then we'll copy the files
            //For this method the user must have write permissions to the executing folder.
            //if (!File.Exists(Path.Combine(executingFolder, "libcef.dll")))
            //{
            //    var libPath = Path.Combine(executingFolder, Environment.Is64BitProcess ? "x64" : "x86");

            //    CopyFilesRecursively(new DirectoryInfo(libPath), new DirectoryInfo(executingFolder));

            //    Directory.Delete("x86", recursive: true);
            //    Directory.Delete("x64", recursive: true);
            //}
            //CefSettings cSettings = new CefSettings();
            //cSettings.MultiThreadedMessageLoop = true;
            //cSettings.CefCommandLineArgs.Add("--disable-web-security", "");
            //cSettings.CefCommandLineArgs.Add("--user-data-dir", "C:\\MyChromeDevUserData");
            //Cef.Initialize(cSettings);

            var browser = new BrowserForm();
            Application.Run(browser);
            //LoadApp();
        }

        //https://stackoverflow.com/a/58779/4583726
        private static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)
        {
            foreach (DirectoryInfo dir in source.GetDirectories())
            {
                CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));
            }

            foreach (FileInfo file in source.GetFiles())
            {
                file.CopyTo(Path.Combine(target.FullName, file.Name));
            }
        }

        //解析程序集失败，会加载对应的程序集
        private static Assembly OnResolveAssembly(object sender, ResolveEventArgs args)
        {
            Assembly executingAssembly = Assembly.GetExecutingAssembly();
            AssemblyName assemblyName = new AssemblyName(args.Name);

            var assemblyAllName = assemblyName.Name + ".dll";
            //加载CefSharp相关库
            if (args.Name.StartsWith("CefSharp"))
            {
                string assemblyPath = Path.Combine(Application.StartupPath, CefSettingInit.CefLibName, assemblyAllName);
                return File.Exists(assemblyPath) ? Assembly.LoadFile(assemblyPath) : null;
            }

            //判断程序集的区域性
            if (!assemblyName.CultureInfo?.Equals(CultureInfo.InvariantCulture) == true)
            {
                assemblyAllName = string.Format(@"{0}\{1}", assemblyName.CultureInfo, assemblyAllName);
            }

            using (Stream stream = executingAssembly.GetManifestResourceStream(assemblyAllName))
            {
                if (stream == null) return null;

                var assemblyRawBytes = new byte[stream.Length];
                stream.Read(assemblyRawBytes, 0, assemblyRawBytes.Length);
                return Assembly.Load(assemblyRawBytes);
            }
        }
        //[MethodImpl(MethodImplOptions.NoInlining)]
        private static void LoadApp()
        {
            //Perform dependency check to make sure all relevant resources are in our output directory.
            //var settings = new CefSettings();

            //Cef.Initialize(settings, performDependencyCheck: false, browserProcessHandler: null);

            //CefSettings cSettings = new CefSettings();
            //cSettings.MultiThreadedMessageLoop = true;
            //cSettings.CefCommandLineArgs.Add("--disable-web-security", "");
            //cSettings.CefCommandLineArgs.Add("--user-data-dir", "C:\\MyChromeDevUserData");
            //Cef.Initialize(cSettings);

            var browser = new BrowserForm();
            Application.Run(browser);
        }
    }
}
